package com.larissa.android.quiz;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.MenuProvider;
import androidx.lifecycle.ViewModelProvider;

import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.larissa.android.quiz.databinding.ActivityMainBinding;

public class MainActivity extends AppCompatActivity {
    public static final String TAG="MainActivity";
    public static final String ANSWER_KEY="answer";

    private TextView textView;
    private View btnTrue;
    private View btnFalse;
    private MainViewModel viewModel;
    private MainMenu menu;

    private ActivityResultLauncher helpLauncher=
            registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),new HelpActivityResult());

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityMainBinding binding=ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        Log.d(TAG,"onCreate() called");

        viewModel=new ViewModelProvider(this).get(MainViewModel.class);
        menu=new MainMenu();

        textView=binding.txQuestion;
        int orientation=getResources().getConfiguration().orientation;
        if(orientation== Configuration.ORIENTATION_PORTRAIT){
            btnFalse=binding.btnFalse;
            btnTrue=binding.btnTrue;
        }else{
            btnFalse=binding.btnClose;
            btnTrue=binding.btnCheck;
        }

        View.OnClickListener listener=new ButtonClick();
        btnTrue.setOnClickListener(listener);
        btnFalse.setOnClickListener(listener);

        showQuestion();
        addMenuProvider(menu);
    }

    private void showQuestion(){
        textView.setText(viewModel.getText());
        if(viewModel.isEnd){
            btnTrue.setEnabled(false);
            btnFalse.setEnabled(false);
            Toast.makeText(this,String.format("%s questions are right",viewModel.rightCount),Toast.LENGTH_LONG).show();
        }
    }

    private void jumpToHelp(){
        Intent intent=new Intent(this,HelpActivity.class);
        intent.putExtra(ANSWER_KEY,viewModel.getAnswer());
        helpLauncher.launch(intent);
    }

    private void invalidQuestion(ActivityResult result){
        if(result.getResultCode()==RESULT_OK){
            viewModel.hasHelped=result.getData().getBooleanExtra(HelpActivity.RESULT_KEY,false);
            Log.d(TAG,String.valueOf(viewModel.hasHelped));
            if(viewModel.hasHelped){
                Toast.makeText(this,"This question is invalid",Toast.LENGTH_SHORT).show();
                // 先使Menu失效，然后系统会调用onCreateMenu()重新创建Menu。
                invalidateMenu();
            }
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d(TAG,"onStart() called");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG,"onResume() called");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG,"onPause() called");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d(TAG,"onStop() called");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG,"onDestroy() called");
        boolean finished=isFinishing();
        Log.d(TAG,String.format("finished: %s",finished));
        removeMenuProvider(menu);
    }

    private class ButtonClick implements View.OnClickListener{
        @Override
        public void onClick(View view) {
            viewModel.checkAnswer(view.getId()==R.id.btn_true|| view.getId()==R.id.btn_check);
            showQuestion();
            menu.enable(R.id.btn_help);
        }
    }

    private class MainMenu implements MenuProvider {
        private Menu mMenu;
        @Override
        public void onCreateMenu(@NonNull Menu menu, @NonNull MenuInflater menuInflater) {
            menuInflater.inflate(R.menu.activity_main,menu);
            mMenu=menu;
            if(viewModel.hasHelped){
                disEnable(R.id.btn_help);
                Toast.makeText(MainActivity.this,"This question is invalid",Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public boolean onMenuItemSelected(@NonNull MenuItem menuItem) {
            switch (menuItem.getItemId()){
                case R.id.btn_help:
                    jumpToHelp();
                    return true;
                default:
                    return false;
            }
        }
        // 使MENU中的HELP无效
        private void disEnable(int id){
            mMenu.findItem(id).setEnabled(false);
        }
        // 使MENU中的HELP有效
        private void enable(int id){
            mMenu.findItem(id).setEnabled(true);
        }
    }

    private class HelpActivityResult implements ActivityResultCallback<ActivityResult>{
        @Override
        public void onActivityResult(ActivityResult result) {
            // MainActivity接收到HelpActivity返回数据后的业务逻辑
            invalidQuestion(result);
        }
    }
}